package com.example.moonshine.baidumap.View.Service;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;

import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;

import com.example.moonshine.baidumap.View.Activity.MainActivity;
import com.example.moonshine.baidumap.Entity.GpsRrsultCodeData;
import com.example.moonshine.baidumap.R;

import com.example.moonshine.baidumap.Util.HttpUtil;
import com.example.moonshine.baidumap.Util.UrlHttpData;
import com.example.moonshine.baidumap.Util.publicUtil;
import com.google.gson.Gson;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

import static android.app.Notification.VISIBILITY_PRIVATE;
import static android.content.ContentValues.TAG;


public class TaskAcceptanceService extends Service {


    publicUtil publicUtil = new publicUtil();
    UrlHttpData urlHttpData = new UrlHttpData();
    HttpUtil httpUtil = new HttpUtil();
    String longitude;  //获取经度
    String latitude;   // 获取维度
    String gpdPoint;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(30000, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(30000, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(30000, TimeUnit.SECONDS)//设置连接超时时间
                .build();
        Request request = new Request.Builder()
                .url(urlHttpData.webSockUrl)
                .build();
//        OkHttpClient client = new OkHttpClient();
        mOkHttpClient.newWebSocket(request, new EchoWebSocketListener());
        mOkHttpClient.dispatcher().executorService().shutdown();
    }


    private final class EchoWebSocketListener extends WebSocketListener {

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            webSocket.send("zhangguian");
            publicUtil.LogShow("连接成功");
        }

        @Override
        public void onMessage(WebSocket webSocket, String text) {
            Log.i("tag", "onMessage: " + text);
        }

        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes) {
            Log.i("tag", "onMessage byteString: " + bytes);
        }

        @Override
        public void onClosing(WebSocket webSocket, int code, String reason) {
            webSocket.close(1000, null);
            Log.i("tag", "onClosing: " + code + "/" + reason);
        }

        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            Log.i("tag", "onClosed: " + code + "/" + reason);
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
            Log.i("tag", "onFailure: " + t.getMessage());
        }
    }

    // 开始服务
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        setTask();
        return START_STICKY;
        // The service is starting, due to a call to startService()


    }

    //销毁服务
    @Override
    public void onDestroy() {
        super.onDestroy();
        publicUtil.LogShow("onDestroy", "被调用");
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void ShowNotifi() {

        Notification.Builder Builder = new Notification.Builder(this);
        //设置图标
        Builder.setSmallIcon(R.drawable.ic_zhiapp);
        //设置标题
        Builder.setContentTitle("您有一条新消息");
        //设置内容信息
        Builder.setContentInfo("点击我可以打开一个新的界面");
        Builder.setAutoCancel(true);
        Builder.setDefaults(Notification.DEFAULT_ALL);
        Builder.setVisibility(VISIBILITY_PRIVATE);
//        Builder.setNumber(number);
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Builder.setContentIntent(pi);
        Notification notification = Builder.build();
        //获取系统的通知管理器,通过系统的管理器发送消息
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        //发送通知,参数(一个通知的编号,要发送的通知对象)
        notificationManager.notify((int) (Math.random() * 100), notification);
    }

    public void setTask() {

        final Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void run() {
                // TODO Auto-generated method stub
                //要做的事情
                ShowNotifi();
                GspData();
                sendGPS();
                handler.postDelayed(this, 1000000);
            }
        };
        handler.postDelayed(runnable, 1000000);
    }


//    static String path = "http://123.249.28.108:8082/pipe-network/GpsUpdate";
//    private LocalReceiver mReceiver;


////        Log.d(TAG, "onCreate: executed");
//        Intent intent = new Intent(this,MainActivity.class);
//        PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
//        Notification notification = new NotificationCompat.Builder(this)
//                .setSmallIcon(R.mipmap.ic_zhiapp)
//                .setContentTitle("智慧官网任务服务已开启")
//                .setContentText("请勿关闭")
//                .setWhen(System.currentTimeMillis())
//                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_zhiapp))
//                .setContentIntent(pi)
//                .build();
//        startForeground(1,notification);

//        UrlHttpData urlHttpData = new UrlHttpData();


//        IntentFilter filter = new IntentFilter();
//        filter.addAction("fragment_home");
//        mReceiver = new LocalReceiver();
//        BroadCastManager.getInstance().registerReceiver(Servicetcp.this, mReceiver, filter);//注册广播接收者
//
//        try {
//            GspData();
//        } catch (Exception e) {
//            e.printStackTrace();
//            Toast.makeText(getApplicationContext(), "定位获取错误", Toast.LENGTH_LONG).show();
//        }


//
//    public final class EchoWebSocketListener extends WebSocketListener {
//        private Handler mDelivery;
//        WebListener http;
//        WebSocket webSocket;
//
//        public void setHttp(WebListener listener) {
//            this.http = listener;
//        }
//
//        private EchoWebSocketListener() {
//        }
//
//        private EchoWebSocketListener urlservice;
//
//        public WebSocketListener getinstace() {
//            if (urlservice == null) {
//                synchronized (EchoWebSocketListener.class) {
//                    if (urlservice == null) {
//                        urlservice = new EchoWebSocketListener();
//                    }
//                }
//            }
//            return urlservice;
//        }
//
//        @Override
//        public void onOpen(WebSocket webSocket, Response response) {
//            this.webSocket = webSocket;
//            mDelivery = new Handler(Looper.getMainLooper());
//            webSocket.send(StaticUser.getUser());
//
//        }
//
//        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
//        @Override
//        public void onMessage(WebSocket webSocket, final String text) {
//            System.out.println("onMessage: " + text);
////            Log.i("EchoWebSocketListener", "发给fragment");
////            Intent intent = new Intent();
////            intent.putExtra("text", text);
////            intent.setAction("fragment_home_left");
////            BroadCastManager.getInstance().sendBroadCast(Servicetcp.this, intent);
////            if (text.equals("101")) {
////
////                SpostHttpMap spostHttpMap = new SpostHttpMap();
////                String result = spostHttpMap.Postmap(path, gpsPoint, StaticUser.getToken(), StaticUser.getUser());
////                if (result.equals("10")) {
////                    Toast.makeText(getApplicationContext(), "位置发送成功", Toast.LENGTH_SHORT).show();
////                } else {
////
////                    Toast.makeText(getApplicationContext(), "位置发送失败", Toast.LENGTH_SHORT).show();
////                }
////
////            }
////            if (text.equals("102")) {
////                messageNotification();
////            }
//
//        }
//
//
//        @Override
//        public void onMessage(WebSocket webSocket, ByteString bytes) {
////            System.out.println("onMessage byteString: " + bytes);
//            http.output("onMessage byteString: " + bytes);
//        }
//
//        @Override
//        public void onClosing(WebSocket webSocket, int code, String reason) {
//            webSocket.close(1000, null);
////            System.out.println("onClosing: " + code + "/" + reason);
//            http.output("onClosing: " + code + "/" + reason);
//        }
//
//        @Override
//        public void onClosed(WebSocket webSocket, int code, String reason) {
//            http.output("onClosed: " + code + "/" + reason);
////            System.out.println("onClosed: " + code + "/" + reason);
//        }
//
//        @Override
//        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
//            try {
//                http.output("onFailure: " + t.getMessage());
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//
//
//        /**
//         * @param s
//         * @return
//         */
//        public boolean sendMessage(String s) {
//            return webSocket.send(s);
//        }
//
//        public boolean closeMessage() {
//            return webSocket.close(1000, "");
//        }
//    }

//    @Override
//    public void onRebind(Intent intent) {
//        super.onRebind(intent);
//        // A client is binding to the service with bindService(),
//        // after onUnbind() has already been called
//    }
//
//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        // The service is no longer used and is being destroyed
//    }


    //    /**
//     * 接收广播后的处理
//     */
//    class LocalReceiver extends BroadcastReceiver {
//
//        public void onReceive(Context context, Intent intent) {
//            //收到广播后的处理
//            String text = intent.getStringExtra("textresult");
//            if (text.equals("3")) {
//                listener.closeMessage();
//                handler.removeCallbacks(runnable);
//            }
//
//            Log.i("tag", "退出传参的数字为" + text);
//        }
//    }
//
//    /**
//     * 基站定位
//     */
////    public class GetIdUtil {
////        private Context mContext;
////        TelephonyManager mTelephonyManager;
////
////        public GetIdUtil(Context context) {
////            this.mContext = context;
////        }
////
////        /**
////         * 获取 基站 信息
////         *
////         * @return
////         */
////
////        public String getBaseStationInformation() {
////            if (mTelephonyManager == null) {
////                mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
////            }
////            // 返回值MCC + MNC （注意：电信的mnc 对应的是 sid）
////            String operator = mTelephonyManager.getNetworkOperator();
////            int mcc = -1;
////            int mnc = -1;
////            if (operator != null && operator.length() > 3) {
////                mcc = Integer.parseInt(operator.substring(0, 3));
////                mnc = Integer.parseInt(operator.substring(3));
////            }
////
////            // 获取邻区基站信息
////
////            @SuppressLint("MissingPermission") List<NeighboringCellInfo> infos = mTelephonyManager.getNeighboringCellInfo();
////            StringBuffer sb = new StringBuffer("总数 : " + infos.size() + "\n");
////
////            for (NeighboringCellInfo info1 : infos) { // 根据邻区总数进行循环
////                sb.append(" LAC : " + info1.getLac()); // 取出当前邻区的LAC
////                sb.append("\n CID : " + info1.getCid()); // 取出当前邻区的CID
////                sb.append("\n BSSS : " + (-113 + 2 * info1.getRssi()) + "\n"); // 获取邻区基站信号强度
////            }
////
////
////            int type = mTelephonyManager.getNetworkType();
////
//////            Toast.makeText(mContext,"type:= "+type,Toast.LENGTH_LONG).show();
////            //需要判断网络类型，因为获取数据的方法不一样
////            if (type == TelephonyManager.NETWORK_TYPE_CDMA        // 电信cdma网
////                    || type == TelephonyManager.NETWORK_TYPE_1xRTT
////                    || type == TelephonyManager.NETWORK_TYPE_EVDO_0
////                    || type == TelephonyManager.NETWORK_TYPE_EVDO_A
////                    || type == TelephonyManager.NETWORK_TYPE_EVDO_B
////                    || type == TelephonyManager.NETWORK_TYPE_LTE) {
////                @SuppressLint("MissingPermission") CdmaCellLocation cdma = (CdmaCellLocation) mTelephonyManager.getCellLocation();
////                if (cdma != null) {
////                    sb.append(" MCC = " + mcc);
////                    latitude = String.valueOf((float) cdma.getBaseStationLatitude() / 14400);
////                    longitude = String.valueOf((float) cdma.getBaseStationLongitude() / 14400);
////                    gpsPoint = latitude + "," + longitude;
////                    sb.append("\n cdma.getBaseStationLatitude()" + latitude + "\n"
////                            + "cdma.getBaseStationLongitude() " + longitude + "\n"
////                            + "cdma.getBaseStationId()(cid)  " + cdma.getBaseStationId()
////                            + "\n  cdma.getNetworkId()(lac)   " + cdma.getNetworkId()
////                            + "\n  cdma.getSystemId()(mnc)   " + cdma.getSystemId());
////                } else {
////                    sb.append("can not get the CdmaCellLocation");
////                }
////
////            } else if (type == TelephonyManager.NETWORK_TYPE_GPRS         // 移动和联通GSM网
////                    || type == TelephonyManager.NETWORK_TYPE_EDGE
////                    || type == TelephonyManager.NETWORK_TYPE_HSDPA
////                    || type == TelephonyManager.NETWORK_TYPE_UMTS
////                    || type == TelephonyManager.NETWORK_TYPE_LTE) {
////                @SuppressLint("MissingPermission") GsmCellLocation gsm = (GsmCellLocation) mTelephonyManager.getCellLocation();
////                if (gsm != null) {
////                    sb.append("  gsm.getCid()(cid)   " + gsm.getCid() + "  \n "//移动联通 cid
////                            + "gsm.getLac()(lac) " + gsm.getLac() + "  \n "             //移动联通 lac
////                            + "gsm.getPsc()  " + gsm.getPsc());
////                } else {
////                    sb.append("can not get the GsmCellLocation");
////                }
////            } else if (type == TelephonyManager.NETWORK_TYPE_UNKNOWN) {
////                Toast.makeText(mContext, "电话卡不可用！", Toast.LENGTH_LONG).show();
////            }
////
////            Log.d("spp", "mTelephonyManager.getNetworkType(); " + mTelephonyManager.getNetworkType());
////            Log.i(TAG, "经度：" + latitude);
////            Log.i(TAG, "纬度：" + longitude);
////            Log.i(TAG, " 获取邻区基站信息:" + sb.toString());
////            return sb.toString();
////        }
////    }
//    @SuppressLint("MissingPermission")
    public void GspData() {
        final LocationManager locationManager;
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        @SuppressLint("MissingPermission") Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        //使用location 来更新EditText的显示
        updateView(location);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 8, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                //当GPS 定位信息发生改变时，更新位置
                updateView(location);
            }

            @Override
            public void onStatusChanged(String provider, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String provider) {
                if (ActivityCompat.checkSelfPermission(TaskAcceptanceService.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(TaskAcceptanceService.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.

                    return;
                }
                updateView(locationManager.getLastKnownLocation(provider));
            }

            @Override
            public void onProviderDisabled(String provider) {

                updateView(null);
            }

        });
    }

    public void updateView(Location newLocation) {
        if (newLocation != null) {
            StringBuffer sb = new StringBuffer();
            sb.append("实时的位置信息：\n");
            sb.append("\n经度");
            sb.append(newLocation.getLongitude());
            sb.append("\n纬度：");
            sb.append(newLocation.getLatitude());
            Log.i(TAG, "经度:" + newLocation.getLongitude());
            Log.i(TAG, "纬度:" + newLocation.getLatitude());
            longitude = newLocation.getLongitude() + "";
            latitude = newLocation.getLatitude() + "";
            try {
                gpdPoint = longitude.substring(0, 10) + "," + latitude.substring(0, 10);
                publicUtil.ToastShow(TaskAcceptanceService.this,gpdPoint);
                Log.i("SER", "经纬度：" + gpdPoint);
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "定位获取错误", Toast.LENGTH_LONG).show();
            }
        }
    }

    public  void sendGPS(){
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final String token= publicUtil.getUserInfo(getBaseContext(),"token","token");
                    final String username = publicUtil.getUserInfo(getBaseContext(),"username","login");
                    String rusult =  httpUtil.getPostGps(username,gpdPoint,urlHttpData.GpsUrl,token);

                    Gson gson = new Gson();
                    GpsRrsultCodeData gpsRrsultCodeData = gson.fromJson(rusult,GpsRrsultCodeData.class);
                    String code= gpsRrsultCodeData.getState();
                    publicUtil.LogShow("结果",code);
                    if (code.equals('1')){
                        publicUtil.LogShow("请求成功");
                    }else {
                        publicUtil.ToastShow(getBaseContext(),"请求失败");
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
//
//
//    public void postGps() {
//        handler = new Handler();
//        runnable = new Runnable() {
//            @Override
//            public void run() {
//                // TODO Auto-generated method stub
//                //要做的事情
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            SpostHttpMap spostHttpMap = new SpostHttpMap();
//                            String result = spostHttpMap.Postmap(path, gpsPoint, StaticUser.getToken(), StaticUser.getUser());
//                            Toast.makeText(Servicetcp.this, "保活", Toast.LENGTH_LONG).show();
//                            if (result.equals("未登录")) {
//                                Intent intent = new Intent();
//                                intent.putExtra("text", "logout");
//                                intent.setAction("fragment_home_left");
//                                BroadCastManager.getInstance().sendBroadCast(Servicetcp.this, intent);
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            Toast.makeText(Servicetcp.this, "gps未获取，请检查是否开启gps定位", Toast.LENGTH_LONG).show();
//                        }
//                    }
//                }).start();
//                handler.postDelayed(this, 10000);
//            }
//        };
//        handler.postDelayed(runnable, 10000);
//    }
//
//    /**
//     * 创建任务栏
//     */
//    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
//    public void messageNotification() {
//        //这里的通知要使用Builder对象来创建
//        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//        //实例化通知
//        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
//
//        //显示在通知栏上的图标是必须的
//        builder.setSmallIcon(R.mipmap.ic_zhiapp);
//        //在通知栏上显示文字信息，可以不写
//        builder.setTicker("你有一条新信息！");
//        //这是状态栏上的信息
//        builder.setContentTitle("你有一条新消息");//标题信息
//        builder.setContentText("有一个井盖丢失，需要你及时处理");//文本信息
//        builder.setWhen(System.currentTimeMillis());//显示发送的时间
//        builder.setContentInfo("Info");//文本的其他信息
//        //设置通知模式，参数如下
//        //Notification.DEFAULT_LIGHTS闪光模式
//        // Notification.DEFAULT_SOUND声音模式
//        // Notification.DEFAULT_VIBRATE震动模式
//        //Notification.DEFAULT_ALL以上三中模式都选
//        builder.setDefaults(Notification.DEFAULT_ALL);
//        builder.setAutoCancel(true);//打开程序后图标消失
//
//        //创建Notification对象,生成对象 16API以上，支持低版本需要使用v4包中的notificationCompat
//        Notification notify = builder.build();
//        //设置消息不能清除
//        notify.flags = Notification.FLAG_NO_CLEAR;
//        //利用系统的Manage发送消息
////        NotificationManager manager = (NotificationManager) getContext().getSystemService(NOTIFICATION_SERVICE);
//        //发送消息
//        //第一个参数是通知的一个唯一标识值，
//        assert notificationManager != null;
//        notificationManager.notify((int) (Math.random() * 100), notify);
//    }
//
//    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
//    @SuppressLint("WrongConstant")
//    public int onStartCommand(Intent intent, int flags, int startId) {
//        Log.d(TAG, "onStartCommand()");
////        GspData();
//        postGps();
//        return  super.onStartCommand(intent, flags, startId);
//    }



